/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

package com.hlkj.pay.util;

import com.hlkj.framework.common.util.web.WebFrameworkUtils;
import com.hlkj.pay.common.constants.TokenConstant;
import jodd.util.StringPool;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author monk@techsun.com
 * @date 2023/06/16 13:23
 */
public class RefererUtils {

    /**
     * bindUrl
     *
     * @return
     */
    public static String domain() {
        // 要通过秘钥的租户id 获取对应的绑定的url
        HttpServletRequest request = WebFrameworkUtils.getRequest();
        String bindUrl = request.getHeader(TokenConstant.BIND_URL);
        if (StringUtils.hasText(bindUrl)) {
            if (bindUrl.endsWith(StringPool.SLASH)) {
                bindUrl = bindUrl.substring(0, bindUrl.length() - 1);
            }
            return bindUrl;
        }
        String referer = request.getHeader(TokenConstant.REFERER);
        if(!StringUtils.hasText(referer)){
            return null;
        }
        String[] split = referer.split(StringPool.SLASH);
        StringBuilder sb = new StringBuilder();
        int size = TokenConstant.urlSplitSize;
        for (int i = 0; i < size; i++) {
            sb.append(split[i]);
            if (i != size) {
                sb.append(StringPool.SLASH);
            }
        }
        return sb.toString();
    }
}
